package List.SequenceList;

import java.util.Arrays;
import java.util.Iterator;

public class SequenceList<T> implements Iterable<T> {

    private T[] elements;//element.length为capacity的值
    //记录数组长度
    private int N;

    public SequenceList(int capacity) {
        this.elements = (T[]) new Object[capacity];
        this.N = 0;
    }

    public void clear() {
        N = 0;//让线性表逻辑上清空
    }

    public Boolean isEmpty() {
        return N == 0;
    }

    public int length() {
        return N;
    }

    public T get(int i) {
        return elements[i];
    }

    public Boolean insert(T t) {
        if (N <= elements.length - 1) {
            elements[N++] = t;
            return true;
        } else {
            return false;
        }
    }

    public Boolean insert(int index, T t) {
        if (index >= elements.length || index < 0) {
            return false;
        }
        for (int i = N - 1; i >= index; i--) {
            elements[i + 1] = elements[i];
        }
        elements[index] = t;
        N++;
        return true;
    }

    public T remove(int index) {
        T t = get(index);
        for (int i = index; i < N - 1; i++) {
            elements[i] = elements[i + 1];
        }
        N--;
        return t;
    }

    public int indexOf(T t) {
        for (int i = 0; i < N; i++) {
            if (elements[i].equals(t)) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public String toString() {
        return "SequenceList{" +
                "elements=" + Arrays.toString(elements) +
                '}';
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            int current = 0;

            @Override
            public boolean hasNext() {
                return current < N;
            }

            @Override
            public T next() {
                return elements[current++];
            }
        };
    }
}
